package com.example.emos.wx.task;

import com.example.emos.wx.entity.MessageEntity;
import com.example.emos.wx.entity.MessageRefEntity;
import com.example.emos.wx.exception.EmosException;
import com.example.emos.wx.service.MessageService;
import com.rabbitmq.client.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class MessageTask {
    @Autowired
    private ConnectionFactory factory;

    @Autowired
    private MessageService messageService;

    /**
     * @Author leikw
     * @Description 根据topic发送消息
     * @Date  2023/2/7 17:14
     */
    public void send(String topic, MessageEntity entity) {
        //增加MongoDB消息 返回主键
        String id = messageService.insertMessage(entity);
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel();
        ) {
            //连接到topic
            channel.queueDeclare(topic, true, false, false, null);

            //构造消息额外参数
            HashMap map = new HashMap();
            map.put("messageId", id);
            AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().headers(map).build();

            //发送消息到topic队列
            channel.basicPublish("", topic, properties, entity.getMsg().getBytes());
            log.debug("消息发送成功");
        } catch (Exception e) {
            log.error("执行异常", e);
            throw new EmosException("向MQ发送消息失败");
        }
    }

    @Async
    public void sendAsync(String topic, MessageEntity entity) {
        send(topic, entity);
    }

    /**
     * @Author leikw
     * @Description 根据topic接收消息 并返回接收到的消息数量
     * @Date  2023/2/7 17:14
     */
    public int receive(String topic) {
        int i = 0;
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel();
        ) {
            //连接到topic
            channel.queueDeclare(topic, true, false, false, null);
            while (true) {
                //接收topic队列中的消息 不自动Ack
                GetResponse response = channel.basicGet(topic, false);
                if (response != null) {
                    //topic队列中没有消息 跳出读取消息循环
                    AMQP.BasicProperties properties = response.getProps();
                    Map<String, Object> map = properties.getHeaders();
                    String messageId = map.get("messageId").toString();
                    byte[] body = response.getBody();
                    String message = new String(body);
                    log.debug("从RabbitMQ接收的消息：" + message);

                    //构造数据保存到MongoDB
                    MessageRefEntity entity = new MessageRefEntity();
                    entity.setMessageId(messageId);
                    entity.setReceiverId(Integer.parseInt(topic));
                    entity.setReadFlag(false);
                    entity.setLastFlag(true);
                    messageService.insertRef(entity);
                    //保存数据后手动ACK
                    long deliveryTag = response.getEnvelope().getDeliveryTag();
                    channel.basicAck(deliveryTag, false);
                    i++;
                }
                else {
                    //topic队列中没有消息 跳出读取消息循环
                    break;
                }
            }
        } catch (Exception e) {
            log.error("执行异常", e);
            throw new EmosException("接收消息失败");
        }
        return i;
    }


    @Async
    public int receiveAsync(String topic) {
        return receive(topic);
    }

    /**
     * @Author leikw
     * @Description 根据topic删除消息队列
     * @Date  2023/2/7 17:14
     */
    public void deleteQueue(String topic){
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel();
        ) {
            channel.queueDelete(topic);
            log.debug("消息队列成功删除");
        }catch (Exception e) {
            log.error("删除队列失败", e);
            throw new EmosException("删除队列失败");
        }
    }

    @Async
    public void deleteQueueAsync(String topic){
        deleteQueue(topic);
    }

}
